//
//  KABMallOrderDetailVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/21.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMallOrderDetailVC.h"
#import "KABMallShopCartTCell.h"
#import "KABMallShoCarHeaderHFView.h"
#import "KABMallSurOrdFooterHFView.h"
#import "KABMallOrdDetInfoTCell.h"
#import "KABModel.h"
#import "ApiManager.h"
#import "XDAFNetworking.h"
#import "GlobalHeader.h"
#import "MBProgressHUD+XDPrompt.h"
#import "WXApiManager.h"
#import "KABMallLogisticVC.h"
#import "KABMallReturnProVC.h"

@interface KABMallOrderDetailVC () <UITableViewDelegate, UITableViewDataSource,KABMallSurOrdFooterHFViewDelegate, WXApiManagerDelegate>

@property (strong, nonatomic) IBOutlet UIView *headerBgView;
@property (weak, nonatomic) IBOutlet UILabel *hNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *hPhoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *hAddressLabel;
@property (strong, nonatomic) IBOutlet UIView *footerBgView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) KABMallSubOrdBackModel *tempOrder;//!< 支付中间用于查询的临时数据

@end

static NSString *const kReuseCellId = @"KABMallShopCartTCell";
static NSString *const kInfoCellId = @"KABMallOrdDetInfoTCell";
static NSString *const kHeaderViewId = @"KABMallShoCarHeaderHFView";
static NSString *const kFooterViewId = @"KABMallSurOrdFooterHFView";

@implementation KABMallOrderDetailVC

#pragma mark - life cycle
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActiveHandle:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"订单详情";
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initSubViews {
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    //
    //    self.tableView.contentInset = UIEdgeInsetsMake(-64 * 2.0, 0, 49.0, 0);
    //    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 49.0, 0);
    
    UINib *headerNib = [UINib nibWithNibName:kHeaderViewId bundle:nil];
    [self.tableView registerNib:headerNib forHeaderFooterViewReuseIdentifier:kHeaderViewId];
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kReuseCellId];
    UINib *infoCellNib = [UINib nibWithNibName:kInfoCellId bundle:nil];
    [self.tableView registerNib:infoCellNib forCellReuseIdentifier:kInfoCellId];
    UINib *footerNib = [UINib nibWithNibName:kFooterViewId bundle:nil];
    [self.tableView registerNib:footerNib forHeaderFooterViewReuseIdentifier:kFooterViewId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 44.0;
//    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionHeaderHeight = 48.0;
//    self.tableView.sectionFooterHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionFooterHeight = 108.0;
    
    self.tableView.tableHeaderView = self.headerBgView;
    if (self.orderDetail.order_type == 1) {
        self.tableView.tableFooterView = self.footerBgView;
    }
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self refreshWholeView];
    if (!self.orderDetail && self.order_id.length) {
        [self requestMallOrderDetail];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (section == 0) ? self.orderDetail.product_list.count : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        KABMallShopCartTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
        [cell configViewWithOrderProItem:self.orderDetail.product_list[indexPath.row] couldSel:NO isEdit:NO];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        KABMallOrdDetInfoTCell *cell = [tableView dequeueReusableCellWithIdentifier:kInfoCellId forIndexPath:indexPath];
        [cell configViewWithOrderDetail:self.orderDetail];
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        KABMallShoCarHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderViewId];
        [view configViewWithOrderDetail:self.orderDetail couldSel:NO wholeSel:NO];
        return view;
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        KABMallSurOrdFooterHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kFooterViewId];
        [view configViewWithOrderDetail:self.orderDetail];
        view.delegate = self;
        return view;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 45.0;
    }
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 108.0;
    }
    return 6.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - KABMallSurOrdFooterHFViewDelegate
- (void)kABMallSurOrdFooterHFView:(KABMallSurOrdFooterHFView *)view section:(NSInteger)section leftBtnTapped:(UIButton *)btn {
    if ([[btn titleForState:UIControlStateNormal] isEqualToString:@"查看物流"]) {
        KABMallLogisticVC *vc = [[KABMallLogisticVC alloc] init];
        vc.logistic_code = self.orderDetail.logistic_code;
        [self showViewController:vc sender:nil];
    }
}
- (void)kABMallSurOrdFooterHFView:(KABMallSurOrdFooterHFView *)view section:(NSInteger)section rightBtnTapped:(UIButton *)btn {
    if (self.orderDetail.order_type == 1) {       // 请求微信支付
        [self requestWxPay:self.orderDetail];
        return;
    } else if (self.orderDetail.order_type == 2) {// 催促发货
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"已催促店家尽快发货"];
        return;
    } else if (self.orderDetail.order_type == 3) {// 确认收货
        [self userConfirmOrder:self.orderDetail];
        return;
    } else if (self.orderDetail.order_type == 4) {// 申请退货
        KABMallReturnProVC *vc = [[KABMallReturnProVC alloc] init];
        vc.orderDetail = self.orderDetail;
        vc.returnSucHandle = ^{
            [self requestMallOrderDetail];
            // 我的订单界面也要刷新
            if (self.userDoActionHandle) {
                self.userDoActionHandle();
                self.userDoActionHandle = nil;
            }
        };
        [self showViewController:vc sender:nil];
        return;
    }
}

#pragma mark - WXApiManagerDelegate
- (void)managerDidRecvPayResponse:(PayResp *)response {
    NSLog(@"微信支付返回：%d, %@, 响应类型:%d", response.errCode, response.errStr, response.type);
    NSLog(@"微信支付：财付通返回:%@", response.returnKey);
//    [self requestProOrderQueryWithOutTradeNo:self.tempOrder.out_trade_no];
}

#pragma mark - event response
- (void)appDidBecomeActiveHandle:(NSNotification *)notification {
    if (self.tempOrder) {;
        NSLog(@"请求微信支付结果");
        // 请求微信支付结果
        [self requestProOrderQueryWithOutTradeNo:self.tempOrder.out_trade_no];
    }
}

#pragma mark - private methods
- (void)payResultProcess {
    [self requestMallOrderDetail];
    // 我的订单界面也要刷新
    if (self.userDoActionHandle) {
        self.userDoActionHandle();
        self.userDoActionHandle = nil;
    }
    // 取消支付中间的句柄
    self.tempOrder = nil;
}

- (void)userConfirmOrder:(KABMallOrderDetail *)orderDetail {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确认已经收货了吗？" message:@"确认收货后，将打款给商家" preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestConfirmOrder:orderDetail];
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
    //    if (self.model.taskList.count >= self.model.totalCount) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    self.hNameLabel.text = self.orderDetail.receiver_name;
    self.hPhoneLabel.text = self.orderDetail.receiver_phone;
    self.hAddressLabel.text = self.orderDetail.receiver_address;
    
    [self.tableView reloadData];
}

#pragma mark - network request
- (void)requestMallOrderDetail {
    // 需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    if (self.order_id.length) {
        [pars setObject:self.order_id forKey:@"order_id"];
    } else if (self.orderDetail.order_id.length) {
        [pars setObject:self.orderDetail.order_id forKey:@"order_id"];
    } else {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"订单号无效"];
        return;
    }
    [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
    [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiProductOrder] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求商城订单详情返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.orderDetail = [KABMallOrderDetail yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求商城订单详情失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestWxPay:(KABMallOrderDetail *)orderDetail {
    // 提示安装微信支付
    if (![WXApi isWXAppInstalled]) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"需要安装微信才能支付"];
        return;
    }
    
    // 请求购物车必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"order_list" : @[orderDetail.order_id]};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiWXPay] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"提交订单返回：%@", responseObject);
        [hud hideAnimated:NO];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.tempOrder = [KABMallSubOrdBackModel yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            [self callWx:self.tempOrder.wx_pay];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"提交订单失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)callWx:(KABMallWxPayPars *)wxPay {
    if (!wxPay) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"微信支付参数错误"];
        return;
    }
    
    // 置位代理
    [WXApiManager sharedManager].delegate = self;
    
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = wxPay.partnerId;
    request.prepayId= wxPay.prepayId;
    request.package = wxPay.package;
    request.nonceStr= wxPay.nonceStr;
    request.timeStamp= wxPay.timeStamp;
    request.sign= wxPay.sign;
    NSLog(@"请求参数:\n partnerId = %@ \n prepayId = %@ \n package = %@ \n nonceStr = %@ \n timeStamp = %zd \n sign = %@ ", request.partnerId, request.prepayId, request.package, request.nonceStr, request.timeStamp, request.sign);
    [WXApi sendReq:request];
}

- (void)requestConfirmOrder:(KABMallOrderDetail *)orderDetail {
    // 请求购物车必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"order_id" : orderDetail.order_id};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiProConfirmOrder] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"确认收货返回：%@", responseObject);
        [hud hideAnimated:NO];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            temp.completionBlock = ^(){
                [self requestMallOrderDetail];
                // 我的订单界面也要刷新
                if (self.userDoActionHandle) {
                    self.userDoActionHandle();
                    self.userDoActionHandle = nil;
                }
            };
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"确认收货失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}
- (void)requestProOrderQueryWithOutTradeNo:(NSString *)out_trade_no {
    // 查询购买结果必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    if (!out_trade_no.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"订单号错误"];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"out_trade_no" : out_trade_no};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiProductOrderQuery] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"查询结果返回：%@", responseObject);
        [hud hideAnimated:NO];
        NSString *str = responseObject[KABGlobalJsonKeyMsg];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            NSDictionary *dic = responseObject[KABGlobalJsonKeyResult];
            str = ([dic[@"result_code"] integerValue] == 1) ? @"支付成功" : @"支付失败";
        }
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:str];
        temp.completionBlock = ^(){
            [self payResultProcess];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"查询结果失败：%@", error);
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
        temp.completionBlock = ^(){
            [self payResultProcess];
        };
    }];
}
#pragma mark - getters and setters

@end
